#coding=utf-8
from datetime import datetime, timedelta
import logging
import re
from RSS.RSSManage import getTmpLib
from Weibo.WeiboManage import getTmpLinkLib
from content import ContentClass, ReplyContent
from models import Images
from photoLib import PhotoLib_Photo
from google.appengine.ext import webapp
from google.appengine.ext import db
from tool import filterNone

__author__ = 'xp'


class deleteOldImage(webapp.RequestHandler):
  def get(self):
      deleteImage()
      #self.render('template/workframe.html',{})

class deleteOldContent(webapp.RequestHandler):
  def get(self):
      deleteContent()

def deleteImage():
    db.delete(PhotoLib_Photo().all().filter('lastUpdateTime <',datetime.now()+timedelta(hours=-24*10)).filter('status =','0').fetch(20))
    #以下是为了修补一个bug而写的代码，之前的咨询删除把过滤咨询中图片的正则写错了导致很多图片没有及时被删除。
    if datetime.now().year>2011 or datetime.now().month>10:
        logging.info('201107')
        return
    lib=getTmpLinkLib()
    logging.info(str(lib.photoLibCode)+'&'+str(datetime.now()+timedelta(hours=-24*10)))
    photo= PhotoLib_Photo().all().filter('photoLibCode =',str(lib.photoLibCode)).filter('lastUpdateTime <',datetime.now()+timedelta(hours=-24*10)).fetch(300)
    for p in photo:
        i=Images().get_by_id(int(p.photoCode))
        if i:
            i.delete()
        p.status='0'
        p.lastUpdateTime=datetime.now()
        p.put()
    logging.info(str(len(photo)))
def deleteContent():
    list=ContentClass().all().filter('lastUpdateTime <',datetime.now()+timedelta(hours=-24*10)).filter('status =','0').fetch(200)
    Rlist=ReplyContent().all().filter('lastUpdateTime <',datetime.now()+timedelta(hours=-24*10)).filter('status =','0').fetch(200)
    logging.info('content:'+str(len(list)))
    for r in Rlist:
        if r.photolist:
            db.delete(db.delete(filterNone(PhotoLib_Photo.get_by_id(r.photolist))))
            db.delete(db.delete(filterNone(Images.get_by_id(r.imglist))))
    db.delete(list)
    db.delete(Rlist)
#    r=ReplyContent().all().filter('code =','a3-11671362202-s11671362202-2011082216112705').fetch(1)
#    logging.info(str(r[0].content.find('\n')))
#    logging.info(str(r[0].content.find('\r')))
#    logging.info(str(r[0].content.find('    ')))
#    lis=ReplyContent().all().filter('lastUpdateTime <',datetime.now()+timedelta(hours=-24*25)).fetch(300)
#    for dc in lis:
#        for img in re.findall('(?i)\[\*TmpImg\/(\d+)\*\]',dc.content.replace('\n','').replace('\r','')):
#            pic=PhotoLib_Photo().all().filter('photoCode',str(img)).fetch(1)
#            if pic:
#                pic[0].status='0'
#                pic[0].lastUpdateTime=datetime.now()
#                db.put(pic)
#            tupian=Images().get_by_id(int(img))
#            if tupian:
#                tupian.delete()
#    logging.info('replay:'+str(len(lis)))
#    db.delete(lis)
